#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Predesys Server - User Interface - MAC addresses management 
@version: 0.2.5
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez
@contact: jajimc@gmail.com"""

import sys
sys.dont_write_bytecode = True
import os
import os.path
DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.path.join(DIR, "../core"))
import security
import exceptions
import usage
import tools
import users
    
def manageArgs(argc, argv):
    """Manages command line input.
    @param argc: Command line argument count
    @type argc: C{int}
    @param argv: Command line input data
    @type argv: C{list}"""  
    if argc == 3 and sys.argv[2] == "list":
        print_address_list()
    elif argc == 5 and sys.argv[2] == "data":
        print_address_data(argv)
    elif argc == 3 and sys.argv[2] == "add":
        add_address_interactively()
    elif argc == 7 and sys.argv[2] == "add":
         add_address(sys.argv)
    elif argc == 3 and sys.argv[2] == "mod":
        modify_address_interactively()
    elif argc == 11 and sys.argv[2] == "mod":
        modify_address(sys.argv)
    elif argc == 4 and sys.argv[2] == "del":
        delete_address(sys.argv[3], True)
    elif argc == 5 and sys.argv[2] == "del" and sys.argv[3] == "-f":
        delete_address(sys.argv[4], False)
    else:
        print usage.get_usage()
        
def print_address_list():
    """Prints every address of every user."""
    addressList = users.get_addresses()
    for address in addressList:
        print address
        
def print_address_data(argv):
    """Prints all fields of an address.
    @param argv: Command line input data
    @type argv: C{list}"""
    address = tools.get_parameter_value(argv, "a")
    if address == None:
        userId = tools.get_parameter_value(argv, "uid")
        if userId == None:
            raise exceptions.Exception("Address/User ID not valid or not specified")
    
    if address != None:
        # Get address' users
        data = users.get_address_users(address)
    else:
        # Get user's addresses
        data = users.get_user_data(userId).get_bt_mac_addresses()
        
    for item in data:
        print item
    
def add_address_interactively():
    """Adds a new address prompting for every field in the command line."""
    security.check_root()
    
    ok = False
    while (not ok):
        address = raw_input("Address: ")
        ok = (address != None and address != "")
        if not ok: print "Data not valid, try again"
        
    ok = False
    while (not ok):
        userId = raw_input("User ID: ")
        ok = (userId != None and userId != "")
        if not ok: print "Data not valid, try again"
    
    users.add_address_user_pair(address, userId)
    print "Address added successfully"

def add_address(argv):
    """Adds a new address.
    @param argv: Command line input data
    @type argv: C{list}"""
    security.check_root()
    
    address = tools.get_parameter_value(argv, "a")
    if address == None or address == "": raise exceptions.Exception("Address not valid or not specified")
    
    userId = tools.get_parameter_value(argv, "uid")
    if userId == None or userId == "": raise exceptions.Exception("User ID not valid or not specified")
    
    users.add_address_user_pair(address, userId)
    print "Address added successfully"

def modify_address_interactively():
    """Modifies an existing address prompting for every field in the command line."""
    security.check_root()
    
    ok = False
    while (not ok):
        oldAddress = raw_input("Old address: ")
        ok = (oldAddress != None and oldAddress != "")
        if not ok: print "Data not valid, try again"

    ok = False
    while (not ok):
        oldUserId = raw_input("Old user ID: ")
        ok = (oldUserId != None and oldUserId != "")
        if not ok: print "Data not valid, try again"
        
    ok = False
    while (not ok):
        newAddress = raw_input("New address: ")
        ok = (newAddress != None and newAddress != "")
        if not ok: print "Data not valid, try again"

    ok = False
    while (not ok):
        newUserId = raw_input("New user ID: ")
        ok = (newUserId != None and newUserId != "")
        if not ok: print "Data not valid, try again"

    
    users.modify_address_user_pair(oldAddress, oldUserId, newAddress, newUserId)
    print "Address modified successfully"

def modify_address(argv):
    """Modifies an existing address.
    @param argv: Command line input data
    @type argv: C{list}"""
    security.check_root()
    
    oldAddress = tools.get_parameter_value(argv, "oa")
    if oldAddress == None or oldAddress == "": raise exceptions.Exception("Old address not valid or not specified")
    
    oldUserId = tools.get_parameter_value(argv, "ouid")
    if oldUserId == None or oldUserId == "": raise exceptions.Exception("Old user ID not valid or not specified")
    
    newAddress = tools.get_parameter_value(argv, "na")
    if newAddress == None or newAddress == "": raise exceptions.Exception("New address not valid or not specified")
    
    newUserId = tools.get_parameter_value(argv, "nuid")
    if newUserId == None or newUserId == "": raise exceptions.Exception("New user ID not valid or not specified")
        
    users.modify_address_user_pair(oldAddress, oldUserId, newAddress, newUserId)
    print "Address modified successfully"

def delete_address(address, confirm):
    """Deletes an existing user group.
    @param address: Address to delete
    @type address: C{str}
    @param confirm: Determines if UI must prompt the user a confirmation.
    @type confirm: C{bool}"""
    security.check_root()
    
    if confirm:
        ok = False
        while (not ok):
            response = raw_input("Are you sure you want to delete address '%s'? [y/n]: " % address)
            response = response.lower()
            ok = (response != None and response != "" and (response == "y" or response == "n"))
            if not ok: print "Answer not valid"
        if response == "n": 
            exit(0)
            
    users.delete_address(address)
    print "Address deleted successfully"
